package com.qcby.xmdemo.service;

import com.qcby.xmdemo.tool.DistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class BusinessService {

    @Autowired
    private DistributedLock distributedLock;

    public void processRequest(String userId) {
        String lockKey = "lock:process:" + userId;
        String lockValue = UUID.randomUUID().toString();
        boolean isLocked = distributedLock.tryLock(lockKey, lockValue, 10, TimeUnit.SECONDS);

        if (isLocked) {
            try {
                // 处理业务逻辑
                System.out.println("Processing request for user: " + userId);
                // 模拟业务处理时间
                Thread.sleep(5000);
                System.out.println("Request processed for user: " + userId);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // 释放锁
                distributedLock.releaseLock(lockKey, lockValue);
            }
        } else {
            // 请求被拒绝或等待
            System.out.println("重复请求，拒绝处理");
        }
    }
}
